import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from flask import Flask, request, send_file, jsonify
from .translator import PDFTranslator, TranslationConfig
from .utils import ArgumentParser, LOG

app = Flask(__name__)

TEMP_FILE_DIR = "flask_temps/"


@app.route('/translation', methods=['POST'])
def translation():
    try:
        input_file = request.files['input_file']
        output_file_format = request.form.get('output_file_format', 'markdown')
        source_language = request.form.get('source_language', 'English')
        target_language = request.form.get('target_language', 'Chinese')

        LOG.debug(f"Received file: {input_file.filename}, source_language: {source_language}, target_language: {target_language}")

        if input_file and input_file.filename:
            input_file_path = TEMP_FILE_DIR + input_file.filename
            LOG.debug(f"Saving file to: {input_file_path}")

            input_file.save(input_file_path)

            output_file_path = Translator.translate_pdf(
                input_file_path,
                output_file_format="pdf",
                source_language=source_language,
                target_language=target_language)

            os.remove(input_file_path)  # 删除临时文件

            output_file_path = os.getcwd() + "/" + output_file_path
            LOG.info(f"Translation completed, output file: {output_file_path}")

            return send_file(output_file_path, as_attachment=True)
    except Exception as e:
        resource = {
            'status': 'error',
            'message': str(e)
        }
        return jsonify(resource), 400


def initialize_translator():
    argument_parser = ArgumentParser()
    args = argument_parser.parse_arguments()

    config = TranslationConfig()
    config.initialize(args)

    global Translator
    Translator = PDFTranslator(config.model_name)


if __name__ == '__main__':
    initialize_translator()

    app.run(host="0.0.0.0", post=5000, debug=True)
